import Taro from '@tarojs/taro';
import {MAINHOST, DEV} from '../config/index';
import Tips from './tips';

declare type Methods = 'GET' | 'OPTIONS' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT';
declare type Headers = { [key: string]: string };

interface Options {
  url: string;
  host?: string;
  method?: Methods;
  data?: any;
  header?: Headers;
}

class Request {
  /**
   * @static 处理options
   * @param {Options | string} opts
   * @param {Datas} data
   * @returns {Options}
   * @memberof Request
   */
  static conbineOptions(opts: Options | string, data: any, method: Methods): Options {
    /**
     * 请求的公共参数
     */
    const commonParame = {};
    typeof opts === 'string' && (opts = {url: opts});
    const header = opts.header ? opts.header : {};
    return {
      data: {...commonParame, ...data},
      method: opts.method || method || 'GET',
      url: MAINHOST + opts.url,
      header: {
        'content-type': 'application/json',
        ...header
      }
    };
  }

  /**
   * @static request请求 基于 Taro.request
   * @param {Options} opts
   */
  static async creatRequests(opts?: Options, data?: any, method: Methods = 'GET') {
    const _opts = this.conbineOptions(opts, data, method);

    // const res = await Taro.request({
    //   url: 'http://localhost:3000/news/portals',
    //   header: {
    //     'content-type': 'application/json'
    //   }
    // });

    //  Taro.request 请求
    const res = await Taro.request(_opts);

    // 请求成功
    if (res.data && res.data.code === 0) {
      return res.data.data;
    }
    // 请求错误
    const d = {
      ...res.data,
      err: (res.data && (res.data.msg || res.data.message)) || `网络错误${res.statusCode}～`
    };
    Tips.toast(d.err);
  }
}

export default Request;
